package rlib

import (
	"sync"
)

type LogItem struct {
	Id  uint64
	Msg string
}

type FileStorageManager struct {
	logs  []LogItem
	nowId uint64

	genIdMutex sync.Mutex

	logsRWMutex sync.RWMutex
}

func (fsm *FileStorageManager) DoLog(msg string) (err error) {
	fsm.logsRWMutex.Lock()
	defer fsm.logsRWMutex.Unlock()
	fsm.logs = append(fsm.logs,
		LogItem{
			Id:  fsm.NewLogId(),
			Msg: msg,
		})
	return
}

func (fsm *FileStorageManager) NewLogId() uint64 {
	fsm.genIdMutex.Lock()
	defer fsm.genIdMutex.Unlock()
	fsm.nowId++
	return fsm.nowId - 1
}

func (fsm *FileStorageManager) PeekFromLogId(logId uint64, uploadLogs *[]string) (err error) {
	fsm.logsRWMutex.RLock()
	defer fsm.logsRWMutex.RUnlock()
	if len(fsm.logs) < int(logId) {
		err = ErrLogIdTooLarge
		return
	}
	for i := 0; i < len(fsm.logs); i++ {
		*uploadLogs = append(*uploadLogs, fsm.logs[i].Msg)
	}
	return
}
